package com.qianfeng.openapi.zuul.filter;

import com.alibaba.fastjson.JSON;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import com.qianfeng.openapi.zuul.exception.ExceptionDict;
import com.qianfeng.openapi.zuul.exception.GatewayException;
import com.qianfeng.openapi.zuul.feign.CacheServiceClient;
import com.qianfeng.openapi.zuul.utils.SysConstant;
import org.apache.commons.lang.StringUtils;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * @Description:
 * @Company: 千锋互联
 * @Author: 李丽婷
 * @Date: 2021/1/5
 * @Time: 上午9:22
 */
@Component
public class TokenFilter  extends ZuulFilter {

    @Resource
    private CacheServiceClient cacheServiceClient;

    @Override
    public String filterType() {
        return FilterConstants.PRE_TYPE;//"pre"
    }

    @Override
    public int filterOrder() {
        return 2;
    }

    @Override
    public boolean shouldFilter() {
        return RequestContext.getCurrentContext().sendZuulResponse();
    }

    @Override
    public Object run() throws ZuulException {
        //1.请求上下文
        RequestContext context = RequestContext.getCurrentContext();
        //2.请求对象
        HttpServletRequest request = context.getRequest();

        try {
            validateToken(request);
        } catch (GatewayException e) {
            context.getResponse().setContentType("application/json;charset=utf-8");//响应内容类型  防止乱码
            context.setSendZuulResponse(false);
            context.setResponseStatusCode(HttpStatus.BAD_REQUEST.value());
            Map<String,Object> map = new HashMap<>();
            map.put("code",e.getCode());//错误码
            map.put("msg",e.getMsg());//错误信息

            String json = JSON.toJSONString(map);

            context.setResponseBody(json);
        }


        return null;
    }

    private void validateToken(HttpServletRequest request) {
        //3.得到用户的token
        String  token = request.getParameter(SysConstant.TOKEN);
        //4.校验token是否正确
        String json = cacheServiceClient.get(SysConstant.CACHE_TOKEN+token);
        //﻿{"accessToken":"0d1263e2-b846-4be8-bb2b-7354dbe3bde7","appId":1,"expireTime":1609381634000,"id":2,"startTime":1609379834000,"userId":1}
        if (StringUtils.isBlank(json)){
            throw  new GatewayException(ExceptionDict.ACCESS_TOKEN_ERROR,"token错误");
        }

        Map<String,Object> map = JSON.parseObject(json);
        long expire = (long)map.get("expireTime");
        long now = System.currentTimeMillis();
        //判断token是否有效
        if (expire<now){
            throw  new GatewayException(ExceptionDict.ACCESS_TOKEN_ERROR,"授权码已经失效");
        }
    }
}
